package com.system.reflect.demo02.impl;

import com.system.reflect.demo02.Interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 在jdk动态代理中使用拦截器
 * @author DELL
 */
public class InterceptorJdkProxy implements InvocationHandler {
    //真实对象
    private Object target;
    //拦截器限定名
    private String interceptorClass = null;

    public  InterceptorJdkProxy(Object target,String interceptorClass){
        this.target = target;
        this.interceptorClass = interceptorClass;
    }

    /**
     * 绑定委托对象并返回一个代理占位
     * @param target
     * @param interceptorClass
     * @return
     */
    public static Object bind(Object target,String interceptorClass){
        //取得代理对象
     return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InterceptorJdkProxy(target, interceptorClass));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (interceptorClass == null){
            //没有拦截器则直接反射原有方法
            return method.invoke(target,args);
        }
        Object result = null;
        //通过反射生成拦截器
        Interceptor interceptor = (Interceptor)Class.forName(interceptorClass).newInstance();
        //调用前置方法
        if (interceptor.before(proxy,target,method,args)){
            //反射原有对象
            result = method.invoke(target, args);
        }else {
            //返回false执行around方法
            interceptor.around(proxy, target, method, args);
        }
        //调用后置方法
        interceptor.after(proxy, target, method, args);
        return result;
    }

}
